<?php
namespace Game\Module;

use Game\Config\Config;
use Game\Traits\Singleton;
use Workerman\Connection\AsyncTcpConnection;
use Exception;

class Socket
{
    use Singleton;
    /**
     * 实例数组
     * @var array
     */
    protected $_socketObject = array();

    /**
     * 获取实例
     * @param $socket_name
     * @param int $is_init
     * @return AsyncTcpConnection
     */
    public function getSocketObject($socket_name,$is_init=0){
        if(!isset($this->_socketObject[$socket_name]) || empty($this->_socketObject[$socket_name]) || $is_init == 1) {
            if($socket_name == "Timer") {
                $host = Config::Timer_Address;
                $port = Config::Timer_Port;

                //实例化游戏对象
            } else if($socket_name == "Processor") {
                $host = Config::Processor_Address;
                $port = Config::Processor_Port;

                //实例化游戏对象
            } else if($socket_name == "GameServer") {
                $host = Config::GameServer_Address;
                $port = Config::GameServer_Port;
            }
            try {
//                Logger::getInstance()->debug("getSocketObject");
                $connect = new AsyncTcpConnection("text://" . $host . ":" . $port);
                $connect->onError = function ($connect, $code, $msg) {
                    echo "Error code:$code msg:$msg\n";
                    Logger::getInstance()->socket("Error code:$code msg:$msg", "ERROR");
                };
                $connect->connect();
            }catch (Exception $exception){
                Logger::getInstance()->socket($exception->getMessage(),"ERROR");
            }
            $this->_socketObject[$socket_name] = $connect;
        }
        return $this->_socketObject[$socket_name];
    }



    /*-------------通用方法--------------*/


    /*
        send message
    */
    public function sendMessageToSocket($socket_name,$message){
        $socketObject = $this->getSocketObject($socket_name);
        $socketObject->send($message);
        return true;
    }


    /*
        close socket
    */
    public function closeSocket($socket_name){
        if(isset($this->_socketObject[$socket_name])) {
            $socketObject = $this->getSocketObject($socket_name);
            $socketObject->close();
        }
        return true;
    }
}